<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\model\OtcOrder;
use app\common\model\OtcShop;
use app\common\model\OtcTrading;
use app\common\model\SbNotice;
use app\common\model\UserPayType;
use app\common\model\UserRankingData;
use think\Db;

/**
 * OTC逻辑
 */
class Shop extends AdminBase
{

    /**
     * 获取会员信息
     */
    public function getOtcInfo($where = [], $field = true)
    {

        $info = $this->modelOtcShop->getInfo($where, $field);

        return $info;
    }



      /**
     * 获取Recharge列表
     */
    public function getShopList($data = [], $field = 'a.* ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where  = ['a.status'=>['neq',-1]];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where['a.user_id|c.username|shop_name'] = $data['search_data'];

        }
        if (!empty($data['wallet_id'])) {
            $where['a.wallet_id'] = $data['wallet_id'];
        }
        if (!empty($data['is_apply'])) {
            $where['a.state'] = ['neq',2];
        }else{
            if (!empty($data['state'])) {
                $where['a.state'] = $data['state'];
            }else{
                $where['a.state'] =['eq',2];
            }
        }
        $where1=['a.state'=>0];
        if (!empty($data['date_type'])){
            switch ($data['date_type']){
                case  1:
                    //今日
                    $where1['a.create_time']=['between',[getTodayStart(),getTodayEnd()]];


                    break;
                case  2:
                    //昨日
                    $where1['a.create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];

                    break;
                case  3:
                    //近七天
                    $where1['a.create_time']=['between',[getTodayStart()-86400*7,getTodayEnd()]];

                    break;
                case  4:
                    //近30天
                    $where1['a.create_time']=['between',[getTodayStart()-86400*30,getTodayEnd()]];

                    break;

            }
        }

        $price=getPrice();
        $eths=[];
        foreach ($price as $k=>$v){
            $where1['a.wallet_id']=6;
            $where1['a.status']=1;
            $where1['a.surplus_total']=$v;
            $arr['name']=$v;
            $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where1)->count();
            $eths[]=$arr;
        }
        $btcs=[];
        foreach ($price as $k=>$v){
            $where1['a.wallet_id']=7;
            $where1['a.status']=1;
            $where1['a.surplus_total']=$v;
            $arr['name']=$v;
            $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where1)->count();
            $btcs[]=$arr;
        }
        $usdts=[];
        foreach ($price as $k=>$v){
            $where1['a.wallet_id']=8;
            $where1['a.status']=1;
            $where1['a.surplus_total']=$v;
            $arr['name']=$v;
            $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where1)->count();
            $usdts[]=$arr;
        }

        $list =  $this->modelOtcShop->alias('a')->field($field)->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->count();


        $esp=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number_do');
        $eth=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number_lock');

        return ['list'=>$list,'count'=>$count,'ect'=>$eth+0,'btc'=>$esp+0,'eths'=>$eths,'btcs'=>$btcs,'usdts'=>$usdts];

    }


    /**
     * 获取Recharge列表
     */
    public function getShopStatisticsList($data = [], $field = 'a.* ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where  = ['a.status'=>['neq',-1]];
        $where1=[];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where1['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where['a.user_id|shop_name|c.username'] = $data['search_data'];

        }
        if (!empty($data['wallet_id'])) {
            $where['a.wallet_id'] = $data['wallet_id'];
        }
        if (!empty($data['is_apply'])) {
            $where['a.state'] = ['neq',2];
        }
        if (!empty($data['state'])) {
            $where['a.state'] = $data['state'];
        }



        $list =  $this->modelOtcShop->alias('a')->field($field)->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);

        $count=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->count();
        foreach ($list as $k=>$v){
            $where1['user_id']=$v['user_id'];
            $where1['shop_id']=$v['id'];
            $where1['state']=2;
            $list[$k]['total_order_success_count']=OtcOrder::where($where1)->count()+UserRankingData::where(['shop_id'=>$v['id'],'type'=>10])->sum('money');

            unset($where1['state']);
            $list[$k]['total_order_count']=OtcOrder::where($where1)->count()+UserRankingData::where(['shop_id'=>$v['id'],'type'=>11])->sum('money');
            if( $list[$k]['total_order_count']>0){
                $list[$k]['success_probability']=format_money($list[$k]['total_order_success_count']/  $list[$k]['total_order_count']*100,2);
            }else{
                $list[$k]['success_probability']=0;
            }

            $list[$k]['total_order_number']=OtcOrder::where($where1)->sum('number')+UserRankingData::where(['shop_id'=>$v['id'],'type'=>12])->sum('money');
            $list[$k]['total_order_profit']=OtcOrder::where($where1)->sum('poundage_number')+UserRankingData::where(['shop_id'=>$v['id'],'type'=>13])->sum('money');
            $list[$k]['total_order_price']=OtcOrder::where($where1)->sum('total')+UserRankingData::where(['shop_id'=>$v['id'],'type'=>14])->sum('money');

        }



        return ['list'=>$list,'count'=>$count];

    }
    /**
     * 会员编辑
     */
    public function shopAdd($data = [])
    {

        $validate_result = $this->validateOtcshop->scene('add')->check($data);
        $url=url('shop_list');
        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateOtcshop->getError()];
        }
        if( $data['pay'][1]!='on' && $data['pay'][2]!='on'  && $data['pay'][3]!='on' ){

            return [RESULT_ERROR, '请选择收款方式'];
        }

        $member=\app\common\model\Member::get(['username|mobile'=>$data['user_name']]);
        if(!$member){
            return [RESULT_ERROR, '用户不存在'];
        }
        $shop=OtcShop::get(['shop_name'=>$data['shop_name'],'user_id'=>['neq',$member['id']]]);
        if($shop){
            return [RESULT_ERROR, '店铺名已被注册'];

        }
        $arr=['','支付宝','微信','银行卡'];
        $pay_type='';
        foreach ($data['pay'] as $k=>$v){
            if($v='on'){
                if(!UserPayType::get( ['user_id'=>$member['id'],'type'=>$k,'status'=>1]) ){
                    return [RESULT_ERROR, '该账户未添加'.$arr[$k].'收款方式'];
                }
                if($k==1){
                    $pay_type.=$k;
                }else{
                    $pay_type.=','.$k;
                }
            }


        }
//        $data['user_id']=$mem['id'];
        Db::startTrans();
        try {



            $data['create_time']=TIME_NOW;
            try {
            foreach ($data['wallet_id'] as $k =>$v){
                if($v='on'){
                    $inf=OtcShop::get(['status'=>1,'user_id'=>$member['id'],'wallet_id'=>$k]);
                    if($inf){
                        $inf->state=2;
                        $inf->save();

                    }else{
                        OtcShop::create([
                            'shop_name'=>$data['shop_name'],
                            'pay_type'=>$pay_type,
                            'wallet_id'=>$k,
                            'user_name'=>$member['username'],
                            'true_name'=>$data['true_name'],
                            'idcard'=>$data['idcard'],
                            'user_id'=>$member['id'],
                            'state'=>2
                        ]);
                    }
                }



            }
                $result=$this->modelMember->setInfo(['id'=>$member['id'],'is_shop'=>1]);



                Db::commit();

                $result && action_log('添加', '添加商铺');
                return $result ? [RESULT_SUCCESS, '商铺添加成功', $url] : [RESULT_ERROR, $this->modelOtcShop->getError()];
            } catch (\Exception $e) {
                return [RESULT_ERROR, $e->getMessage()];

            }




        } catch (\Exception $e) {
            return [RESULT_ERROR, $e->getMessage()];
        }

    }



    /**
     * 会员编辑
     */
    public function shopEdit($data = [])
    {

        $validate_result = $this->validateOtcshop->scene('edit')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateOtcshop->getError()];
        }
//        $mem = \app\common\model\Member::get(['username'=>$data['user_name']]);{
//            if(!$mem){
//                return [RESULT_ERROR,'用户不存在'];
//            }
//        }
//        if(empty($data['id'])){
//            $info=OtcShop::get(['status'=>1,'user_id'=>$mem['id'],'wallet_id'=>$data['wallet_id']]);
//            if($info){
//                return [RESULT_ERROR,'此用户已是此法币商家'];
//            }
////        }
//        $data['user_id']=$mem['id'];
        Db::startTrans();
        try {


            $url=url('shop_list');
            $info=$this->modelOtcShop->getInfo(['id'=>$data['id']]);
            $data['cancel_number']=$info['cancel_number'];
            $result = $this->modelOtcShop->setInfo($data);
            if( !empty($data['state']) && $data['state']==2){

                $data['adopt_time']=TIME_NOW;

                $this->modelMember->setInfo(['id'=>$info['user_id'],'is_shop'=>1]);
                SbNotice::create([
                    'type'=>1,
                    'user_id'=>$info['user_id'],
                    'wallet_id'=>$info['wallet_id']
                ]);
                user_notice($info['user_id'],'您的店铺已通过审核');
            }
            if( !empty($data['state'])){
                $url=url('apply_shop_list');

            }
            Db::commit();
            if(empty($data['id'])){
                $result && action_log('添加', '添加商铺，id：' . $result);
                return $result ? [RESULT_SUCCESS, '商铺添加成功', $url] : [RESULT_ERROR, $this->modelOtcShop->getError()];
            }else{
                $result && action_log('编辑', '编辑商铺，id：' . $data['id']);
                return $result ? [RESULT_SUCCESS, '商铺编辑成功', $url] : [RESULT_ERROR, $this->modelOtcShop->getError()];
            }

        } catch (\Exception $e) {
            return [RESULT_ERROR, $e->getMessage()];
        }

    }


    /**
     *审核商铺
     */
    public function update_info($where = [])
    {

//        dd($where);
        Db::startTrans();
        try{
            if( !empty($where['state']) ){
                if(is_array($where['ids'])){
                    foreach ($where['ids'] as $k=>$v){
                        $info=$this->modelOtcShop->getInfo(['id'=>$v]);
                        if($where['state']==2){
                            \app\common\model\Member::where(['id'=>$info['user_id']])->update(['is_shop'=>1]);

                            SbNotice::create([
                                'type'=>1,
                                'user_id'=>$info['user_id'],
                                'wallet_id'=>$info['wallet_id']
                            ]);
                            user_notice($info['user_id'],'您申请的店铺已通过审核，请第一时间转入店铺押金，避免店铺无法正常营业，系统已默认给您的店铺已开启《抢单“智能”匹配模式》，请前往店铺首页设置营业开始时间和结束时间。');
                        }else{
                            user_notice($info['user_id'],'您的店铺未通过审核,请修改店铺信息后重新提交');
                        }

                        OtcShop::where(['id'=>$v])->update(['state'=>$where['state']]);
                    }
                }else{
                    $info=$this->modelOtcShop->getInfo(['id'=>$where['ids']]);
                    if($where['state']==2){
                        \app\common\model\Member::where(['id'=>$info['user_id']])->update(['is_shop'=>1]);

                        SbNotice::create([
                            'type'=>1,
                            'user_id'=>$info['user_id'],
                            'wallet_id'=>$info['wallet_id']
                        ]);
                        user_notice($info['user_id'],'您申请的店铺已通过审核，请第一时间转入店铺押金，避免店铺无法正常营业，系统已默认给您的店铺已开启《抢单“智能”匹配模式》，请前往店铺首页设置营业开始时间和结束时间。');
                    }else{
                        user_notice($info['user_id'],'您的店铺未通过审核,请修改店铺信息后重新提交');
                    }

                    OtcShop::where(['id'=>$where['ids']])->update(['state'=>$where['state'],'poundage'=>getConfig('otc_apply_shop_poundage')]);
                }



            }else{
                if(isset($where['is_release']) ){
                    if($where['is_release']==0){
                        $where['penalty_time']=time()+86400;
                    }

                }
                if(isset($where['is_match']) ){
                    if($where['is_match']==0){
                        $where['no_match_time']=time()+86400;
                    }

                }
                $this->modelOtcShop->setInfo($where);
            }
            Db::commit();
            return [RESULT_SUCCESS, '操作成功'];
        }catch (\Exception $e){
            Db::rollback();
            return  [RESULT_ERROR, $e->getMessage()];
        }



    }


    /**
     * 获取商铺转入法币列表
     */
    public function getShopCurrencyList($data = [], $field = 'a.*,c.username,c.mobile', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where  = ['a.status'=>['neq',-1],'type'=>23];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where['a.user_id|c.username|s.shop_name'] = $data['search_data'];

        }
        if (!empty($data['form_wallet_id'])) {
            $where['a.form_wallet_id'] = $data['form_wallet_id'];
        }
        if (!empty($data['state'])) {
            $where['a.state'] = $data['state'];
        }



        $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);

        $count=$this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->count();

        return ['list'=>$list,'count'=>$count];

    }

    /**
     *审核商铺转入法币
     */
    public function shop_currency_check($where = [])
    {


        $info= $this->modelTransfer->getInfo(['id'=>$where['id']]);
//        dd($info);
        $where['admin_name']=session('member_info.username');
        $result = $this->modelTransfer->setInfo($where);

        if($where['state']==1){
            $do=$info->towallet->getData('symbol').'_do';
            $account= $this->modelEthAccount->where(['user_id'=>$info['user_id']])->find();
            $account->$do+=$info['money'];
            $account->save();
            $this->modelEthAccountLog->setInfo([
                'wallet_id'=>$info['to_wallet_id'],
                'number'=>$info['number'],
                'before_blance'=>$account->$do-$info['money'],
                'after_blance'=>$account->$do,
                'user_id'=>$account['user_id'],
                'type'=>8,
                'remark'=>'从商铺转入法币',
                'is_add'=>1
            ]);
        }else{
            OtcShop::where(['id'=>$info['shop_id']])->setInc('number_do',$info['number']);
        }


        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];
    }






}
